package com.information.manage.basic.dataOperator;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.information.manage.basic.model.entity.DepartmentDO;
import com.information.manage.basic.common.recycling.RecoveryDataOperateManager;
import com.information.manage.basic.common.recycling.RecoveryDataOperator;
import com.information.manage.basic.common.recycling.RecoveryException;
import com.information.manage.basic.mapper.DepLeaderMapper;
import com.information.manage.basic.mapper.DepartmentMapper;
import com.information.manage.basic.model.entity.DepLeaderDO;
import com.information.manage.basic.service.DepartmentService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

@Component
public class DepartmentRecoveryDataOperator implements RecoveryDataOperator {

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private DepartmentService departmentService;

    @Resource
    private DepLeaderMapper depLeaderMapper;

    @Resource
    private RecoveryDataOperateManager recoveryDataOperateManager;


    @PostConstruct
    public void init(){
        recoveryDataOperateManager.addDataOperate(this);
    }

    @Override
    public void deleteData(Class entityClass, List<Integer> ids) {
        //删除部门负责人
        depLeaderMapper.delete(new LambdaQueryWrapper<DepLeaderDO>().in(DepLeaderDO::getDepartmentId, ids));
        for (Integer id : ids) {
            //判断需要删除的部门的子部门是否存在 如果存在则不允许删除
            Integer childCount = departmentMapper.selectCount(new LambdaQueryWrapper<DepartmentDO>()
                    .eq(DepartmentDO::getParentId, id));
            if (childCount > 0) throw new RuntimeException("存在子部门");
            //判断需要删除的部门
            DepartmentDO departmentDO = departmentMapper.selectOne(new LambdaQueryWrapper<DepartmentDO>().eq(DepartmentDO::getId, id));
            if (departmentDO == null) throw new RuntimeException("部门不存在");
            //筛选层级在当前id后面的部门数据  其中已按层级排序 小->大
            List<DepartmentDO> departmentDOList = departmentMapper.queryDepartmentListByPidAndSequence(departmentDO.getTypeCollection(), departmentDO.getParentId(), departmentDO.getSequence());
            for (DepartmentDO aDo : departmentDOList) { //修改其后面的部门层级 上移
                Boolean aBoolean = departmentService.moveDepartment(aDo.getId(), true);
                //如果执行其中某个执行错误 回滚数据
                if (aBoolean == false) throw new RuntimeException("移动部门出错");
            }
            int resultCount = departmentMapper.deleteById(id);
            if (resultCount <= 0) {
                throw new RecoveryException("删除部门出错, id: " + id);
            }
        }
    }

    @Override
    public List<Class> dependencies() {
        return Collections.EMPTY_LIST;
    }

    @Override
    public Class getEntityClass() {
        return DepartmentDO.class;
    }
}
